<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/12/10
 * Time: 23:13
 */

namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Member;
use think\captcha\Captcha;
use think\Cookie;
use think\Session;

class Login extends AdminBase
{
    /**
     * 要生成验证码的标识
     * @var string
     */
    private $_verifyAuthToken = 'admin';

    /**
     * 登录页面
     * @return mixed
     */
    public function index()
    {
        //已登录,跳转到首页
        if ($this->checkLoginStatus()) {
            $this->redirect('Index/index');
        }
        return $this->fetch('login/index');
    }

    /**
     * 登录验证码
     * @return \think\Response
     */
    public function verify()
    {
        if ($this->checkLoginStatus()) {
            header('Location: ' . url('Index/index'));
            exit;
        }
        ob_end_clean();
        $verify = new Captcha(config('verify'));
        return $verify->entry($this->_verifyAuthToken);
    }

    /**
     * 验证登录信息
     */
    public function runLogin()
    {
        $rebackUrl = url('login/index');
        if (!$this->request->isAjax()) {
            $this->error("提交方式错误！", $rebackUrl);
        } else {

            $verify = new Captcha();
            if (!$verify->check($this->request->param('verify'), $this->_verifyAuthToken)) {
                $this->error('验证码错误', $rebackUrl);
            }

            $username = $this->request->param('username');
            $password = $this->request->param('password');

            if (!$username) {
                $this->error('用户名不能为空', $rebackUrl);
            }

            $userInfo = Member::get(['name' => $username]);

            if (!$userInfo) {
                $this->error('用户名或密码错误', $rebackUrl);
            }
            $this->createLoginStatus($userInfo);
            $this->success('恭喜您，登陆成功', url('Index/index'));
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        Session::destroy();
        Cookie::delete($this->authCookieName);
        $this->redirect('Login/index');
    }
}